package org.nothing.ordermaster.converter;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.nothing.ordermaster.dto.OrderDTO;
import org.nothing.ordermaster.entity.OrderDetail;
import org.nothing.ordermaster.enums.ResultEnum;
import org.nothing.ordermaster.exception.SellException;
import org.nothing.ordermaster.form.OrderForm;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class OrderForm2OrderDTOConverter {
    public static OrderDTO convert(OrderForm orderForm)
    {
        Gson gson = new Gson();
        List<OrderDetail> orderDetailList = new ArrayList<OrderDetail>();
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());
        try {
            // 将 OrderForm 转换成 OrderDTO
            // gson.fromJson(String json, Type typeOfT);
            // 此处对于TypeToken的用法一知半解
            orderDetailList = gson.fromJson(orderForm.getItems(), new TypeToken<List<OrderDetail>>(){}.getType());
        } catch (JsonSyntaxException e) {
            log.error("【对象转换】错误, string={}", orderForm.getItems());
            // 抛出自定义异常: "参数不正确"
            throw new SellException(ResultEnum.PARAM_ERROR);
        }
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }

}
